package com.taxigang.client.uibinder;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasKeyPressHandlers;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestionEvent;
import com.google.gwt.user.client.ui.SuggestionHandler;
import com.taxigang.client.Authenication;
import com.taxigang.client.Authenication.AuthStatus;
import com.taxigang.client.Authenication.Provider;
import com.taxigang.client.Authenication.Status;
import com.taxigang.client.Session;
import com.taxigang.client.TaxiGangHandler;
import com.taxigang.client.TaxiGangHandler.Success;
import com.taxigang.client.TaxigangMode;
import com.taxigang.client.facebook.FacebookApi;
import com.taxigang.client.facebook.FacebookFactory;
import com.taxigang.client.facebook.GetUserDetailsCallback;
import com.taxigang.client.facebook.ThenGetUserDetails;
import com.taxigang.client.facebook.ThenGetUserDetailsMobileCreate;
import com.taxigang.client.facebook.ThenGetUserDetailsMobileJoin;
import com.taxigang.client.facebook.ThenGetUserDetailsMobileMyTaxiGang;
import com.taxigang.client.micro.TaxiGangCreator;
import com.taxigang.client.ui.ButtonType;
import com.taxigang.client.ui.map.JoinView;
import com.taxigang.client.ui.map.MapView;
import com.taxigang.client.ui.map.MapView.PanelType;
import com.taxigang.client.ui.map.MapView.TextBoxType;
import com.taxigang.client.ui.map.MobileNavigatorManager;
import com.taxigang.client.ui.map.NavigatorManager;
import com.taxigang.client.ui.map.ProcessingDialog;
import com.taxigang.client.ui.map.SearchView;
import com.taxigang.client.uibinder_mobile.TaxiGangMobile;
import com.taxigang.shared.ChitInfo;
import com.taxigang.shared.LoginInfo;
import com.taxigang.shared.RouteInfo;
import com.taxigang.shared.TaxiCompanyInfo;
import com.taxigang.shared.TaxiGangInfo;

public class TaxiGangPresenter {

	public enum CreateJoinMode {CREATE,JOIN, MYTAXIGANG, LOGIN};
	private MapView mapView;
	private SearchView searchView;
	private JoinView joinView;
	private boolean userAgentMobile;
	public TaxiGangPresenter(){
		userAgentMobile =Session.getInstance().getIsUserAgentMobile();
	}

	public void setMapView(MapView mapView, JoinView joinView){
		this.mapView = mapView;
		this.joinView = joinView;
		this.searchView = mapView.getSearchView();
		bindDisplay();

	}
	private static TaxiGangPresenter instance;

	public static TaxiGangPresenter getInstance(){
		if (instance==null){
			instance = new TaxiGangPresenter();
		}
		return instance;
	}


	private void bindDisplay(){

		for (final TextBoxType t : TextBoxType.values()){
			if (!userAgentMobile){

//				HasKeyPressHandlers keyPressHandler = searchView.getTextBox(t);
//				keyPressHandler.addKeyPressHandler(new KeyPressHandler() {
//
//					@Override
//					public void onKeyPress(KeyPressEvent event) {
//
//						if (KeyCodes.KEY_ENTER == event.getNativeEvent().getKeyCode() || KeyCodes.KEY_TAB == event.getNativeEvent().getKeyCode()){
//							fireOK(t);
//						}
//
//					}
//				});
			}

			SuggestBox suggestBox =  searchView.getSuggestBox(t);

			suggestBox.addEventHandler(new SuggestionHandler(){

				@Override
				public void onSuggestionSelected(SuggestionEvent event) {
					fireOK(t);
				}

			});

	}



	searchView.getOKTimeButton().addClickHandler(new ClickHandler() {

		@Override
		public void onClick(ClickEvent event) {
			searchView.updateDepartureTime();

			searchView.setMode(SearchView.SearchDisplayMode.SEARCH_CREATE);
		}
	});



	//search & create

	searchView.getButton(ButtonType.Create).addClickHandler(new ClickHandler() {
		public void onClick(ClickEvent event) {

			create();
		}

	});

	joinView.getJoinButton().addClickHandler(new ClickHandler() {
		public void onClick(ClickEvent event) {

			join();
		}

	});


	searchView.getButton(ButtonType.Search).addClickHandler(new ClickHandler() {
		public void onClick(ClickEvent event) {
			Log.info("SEARCH");
			if (userAgentMobile){

				String start = searchView.getTextBoxText(TextBoxType.START).getText();
				Session.getInstance().getSearchTaxiGangInfo().setStart(start);				

				//enterStartAddress(Session.getInstance().getSearchTaxiGangInfo());

				String destination = searchView.getTextBoxText(TextBoxType.DESTINATION).getText().trim();				
				Session.getInstance().getSearchTaxiGangInfo().setDestination(destination);			


				searchView.updateDepartureTime();

				MobileNavigatorManager.searchForTaxiGangs(start, destination,(TaxiGangMobile)searchView);

				//TaxiGangHandler.getInstance().searchForTaxiGangs();
				ProcessingDialog.show(TaxiGangCreator.taxiGangConstants.search());

			} else {
				if (checkStart() != null && checkDestination()!= null){
					searchView.updateDepartureTime();
					TaxiGangHandler.getInstance().searchForTaxiGangs();
					ProcessingDialog.show(TaxiGangCreator.taxiGangConstants.search());
				}
			}
		}
	});


}

public void myTaxiGang(boolean showLoginOnLoggedOut){
	Log.info("MYTAXIGANG:"+showLoginOnLoggedOut);
	//TaxiGangHandler.getInstance().getTaxiCompanies(Session.getInstance().getPostalCode());
	if (Authenication.getInstance().getAuthStatus()==AuthStatus.NotLoggedIn){
		login(CreateJoinMode.MYTAXIGANG,showLoginOnLoggedOut);
	} else {
		TaxiGangHandler.getInstance().searchForMyTaxiGangs(Success.NONE,null);
	}

}

public void create(){
	Log.info("CREATE");
	//TaxiGangHandler.getInstance().getTaxiCompanies(Session.getInstance().getPostalCode());
	Log.debug("auth status="+Authenication.getInstance().getAuthStatus());
	if (Authenication.getInstance().getAuthStatus()==AuthStatus.NotLoggedIn){
		mapView.setPanelToShowOnLogin(PanelType.MOBILENUMBER);
		login(CreateJoinMode.CREATE,true);
	} else {
		//myTaxiGangsWidget.getHideable().show();
		Session session = Session.getInstance();
		searchView.updateDepartureTime();

		String start = searchView.getTextBoxText(TextBoxType.START).getText().trim();				
		String destination = searchView.getTextBoxText(TextBoxType.DESTINATION).getText().trim();				

		TaxiGangInfo info = session.getSearchTaxiGangInfo();
		info.setStart(start);
		info.setDestination(destination);

		session.getSearchTaxiGangInfo().setStart(start);
		Session.getInstance().setCreateJoin(CreateJoinMode.CREATE);
		if (session.getIsUserAgentMobile()){
			MobileNavigatorManager.setUpForCreation(info,(TaxiGangMobile)searchView);
		} else {
			NavigatorManager.setUpForCreation(info,(SearchAndCreate)searchView,mapView);
		}
		//taxiGangHandler.createTaxiGang();

	}

}


public void createWithWait(ChitInfo chit){
	ProcessingDialog.show(TaxiGangCreator.taxiGangConstants.processing());
	TaxiGangHandler.getInstance().createTaxiGang(chit);
}
public void joinWithWait(ChitInfo chit){
	ProcessingDialog.show(TaxiGangCreator.taxiGangConstants.processing());
	TaxiGangHandler.getInstance().joinTaxiGang(chit);
}
public void join(){
	//cancel invitation mode
	Session.getInstance().setRef(null);
	Session.getInstance().setCreateJoin(CreateJoinMode.JOIN);
	Log.info("JOIN");
	Log.debug("auth status="+Authenication.getInstance().getAuthStatus());
	if (Authenication.getInstance().getAuthStatus()==AuthStatus.NotLoggedIn){
		if (TaxigangMode.TAXIGANG == Session.getInstance().getMode()){
			mapView.setPanelToShowOnLogin(PanelType.MOBILENUMBER);
		}else{
			mapView.setPanelToShowOnLogin(PanelType.SUGGESTION);
		}
		login(CreateJoinMode.JOIN,true);
	} else {
		//show Mobilnummer window
		mapView.show(PanelType.MOBILENUMBER);
	}

}

public void login(CreateJoinMode mode,boolean showLoginOnLoggedOut) {
	ThenGetUserDetails thenGetUserDetails = null;
	switch (mode){
	case CREATE:
		thenGetUserDetails = new ThenGetUserDetailsMobileCreate();
		break;
	case JOIN:
		thenGetUserDetails = new ThenGetUserDetailsMobileJoin();
		break;
	case MYTAXIGANG:
		thenGetUserDetails = new ThenGetUserDetailsMobileMyTaxiGang();
		break;
	case LOGIN:
		FacebookApi.fbLogin();
		break;

	}
	if (mode != CreateJoinMode.LOGIN){
		final GetUserDetailsCallback getUserDetailsCallback =  new GetUserDetailsCallback(thenGetUserDetails,showLoginOnLoggedOut);
		Command command = new Command(){
			@Override
			public void execute(){
				FacebookApi.waitForAPI(getUserDetailsCallback);
			}
		};
		FacebookFactory.createFBConnection(null,command);
	}
}

public void fireOK(TextBoxType textBoxType) {
	switch (textBoxType){
	case START:

		String start = checkStart();
		if (start !=null){
			//				searchView.getTextBoxText(TextBoxType.START).setText("");
			Log.info("updateStart="+start);
			Session.getInstance().getSearchTaxiGangInfo().setStart(start);				
			enterStart(Session.getInstance().getSearchTaxiGangInfo());
			if (TaxigangMode.PARTNER == Session.getInstance().getMode()){
				searchView.setMode(SearchView.SearchDisplayMode.SEARCH_CREATE);
			} else {
				searchView.setMode(SearchView.SearchDisplayMode.DESTINATION);
			}

			mapView.hideGuide();
		}
		break;
	case DESTINATION:
		String destination = searchView.getTextBoxText(TextBoxType.DESTINATION).getText();
		Log.info("updateDestination="+destination);
		Session.getInstance().getSearchTaxiGangInfo().setDestination(destination);
		enterDestination(Session.getInstance().getSearchTaxiGangInfo());
		searchView.setMode(SearchView.SearchDisplayMode.SEARCH_CREATE);

		break;
	}
}

private String checkAddress(TextBoxType textBoxType, String enterText){
	String address = searchView.getTextBoxText(textBoxType).getText();
	Log.info("checkAddress="+address);
	if (address != null && address.trim().length() > 0){
		return address;
	}else {
		Window.alert(enterText);
		return null;
	}

}
private String checkStart(){
	return checkAddress(TextBoxType.START, TaxiGangCreator.taxiGangConstants.enterTheAddressTobegin());
}
private String checkDestination(){
	return checkAddress(TextBoxType.DESTINATION, TaxiGangCreator.taxiGangConstants.enterTheAddressToend());
}


public void enterStart(TaxiGangInfo taxiGangInfo){
	Log.info("enterStart="+taxiGangInfo.getStart());
	if (mapView != null){
		mapView.createStartMarker(taxiGangInfo.getStart(),false);
	}

}

public void enterDestination(TaxiGangInfo taxiGangInfo){

	Log.info("enterDest="+taxiGangInfo.getDestination());
	if (mapView != null){
		mapView.createDestinationMarker(taxiGangInfo.getDestination(),true);		
	}
}


public void displayMessages(){

	mapView.show(PanelType.MESSAGES);
}

public void showSuccess(TaxiGangHandler.Success success){
	switch (success){
	case NONE:
		break;

	case UPDATE:
		break;

	case JOIN:
		mapView.show(PanelType.CONGRATULATIONS_JOIN);
		//congratulationsJoinDialog.getHideable().show();
		break;

	case CREATE:
		mapView.show(PanelType.CONGRATULATIONS_CREATE);
	}

}


public void resetSuggestions(){
	Window.alert("TODO:resetSuggestions");

	//		if (
	//				Session.getInstance().getUserAgent()==UserAgent.PC ||
	//				Session.getInstance().getUserAgent()==UserAgent.PC_WEBKIT ||
	//				Session.getInstance().getUserAgent()==UserAgent.FB_WEBKIT ||
	//				Session.getInstance().getUserAgent()==UserAgent.FB
	//		){
	//			suggestionView.getHideable().hide();
	//		}
	//		mapView.resetSuggestion();

}

public void displayTaxiGangsList(){
	Session session = Session.getInstance();
	TaxiGangInfo[] taxigangInfoList = session.getTaxiGangSearchResultList();
	if (taxigangInfoList == null || taxigangInfoList.length == 0){
		mapView.show(PanelType.SORRY);

		//microNoTaxiGangsWidget.getHideable().show();			
	}else{
		Session.getInstance().setCurrentSuggestionIndex(0);
		mapView.show(PanelType.SUGGESTION);

		//			suggestionView.setButtonMode(ButtonMode.LIST_TAXIGANGS);
		//			session.setCurrentSuggestionIndex(0);
		//			suggestionView.showSuggestionInText(taxigangInfoList[0]);
		//			mapView.showSuggestionInMap(taxigangInfoList[0]);
	}

}

public void displayPartner(RouteInfo partnerInfo){
	//TODO cleanup
	//		//Todo
	//		//if (partnerInfo == null){
	//		if (false){
	//			mapView.show(PanelType.SORRY);
	//		}else{
	//			mapView.show(PanelType.SEARCH);
	//			mapView.createStartMarker("Westendstr. 80", "Munich", true);
	//
	//			Geolocator geolocation = new Geolocator();
	//			geolocation.runGeolocation(mapView);
	//
	//			//			suggestionView.setButtonMode(ButtonMode.LIST_TAXIGANGS);
	//			//			session.setCurrentSuggestionIndex(0);
	//			//			suggestionView.showSuggestionInText(taxigangInfoList[0]);
	//			//			mapView.showSuggestionInMap(taxigangInfoList[0]);
	//		}

}

//	public void updateTaxiCompanies(String postalCode, TaxiCompanyInfo[] listtaxiCompany) {
//		mapView.setTaxiCompanyList(postalCode, listtaxiCompany);
//
//	}

public void authenticationComplete(boolean showLoginOnLoggedout){
	//Log.info("TaxiGangPresenter:authenticationComplete");

	AuthStatus status = Authenication.getInstance().getAuthStatus();
	switch(status){
	case LoggedInGoogle:
		TaxiGangHandler.getInstance().searchForMyTaxiGangs(Success.NONE,null);
		break;

	case LoggedInFacebook:
		Log.info("TaxiGangPresenter:authenticationComplete:LoggedInFacebook");
		mapView.setLoggedIn(Provider.Facebook);
		mapView.showLoginButton(false);
		break;

	case NotLoggedIn:
		Log.info("TaxiGangPresenter:authenticationComplete:NotLoggedIn:"+showLoginOnLoggedout);

		mapView.showLoginButton(true);
		if (showLoginOnLoggedout){
			mapView.setLoggedOut("from TaxiGangPresenter:authenticationComplete");
		}


		break;

	case LoggedInTmp:
		TaxiGangHandler.getInstance().searchForMyTaxiGangs(Success.NONE,null);
		break;
	}

}

public void onFacebookLogin() {
	Log.info("onFacebookLogin");
	Authenication.getInstance().setAuthStatus(Provider.Facebook, Status.LoggedIn);
	FacebookApi.waitUntilUserDetailsReady(new ThenGetUserDetails());
	mapView.setLoggedIn(Provider.Facebook);
}

public void onFacebookLogout() {
	//TODO this fires when try to establish login status
	//disable for future investigation
	if (true) return;
	LoginInfo loginInfo = new LoginInfo();
	Session.getInstance().setLoginInfo(loginInfo); //TODO
	mapView.setLoggedOut("TaxigangPresenter:onFacebookLogout");
	Authenication.getInstance().getLogedinResolved(Provider.Facebook, Status.LoggedIn);
}

public void displayMyTaxiGangsList() {
	TaxiGangInfo[] myTaxiGangInfoList = Session.getInstance().getMyTaxiGangInfoList();
	//if (TaxiGangMain.getSession().getUserAgent() != UserAgent.IPHONE){
	if (myTaxiGangInfoList.length == 0){
		mapView.show(PanelType.SEARCH);
		Alert.alert(null,"Taxigang",TaxiGangCreator.taxiGangConstants.youHaveNoActiveTaxiGangs(),false,"422px");

	} else {
		mapView.show(PanelType.MYTAXIGANGS);
	}

}

public void showCantLeave() {
	Window.alert("TODO:showCantLeave");

}

//	public void initOracle() {
//		mapView.initOracle();
//
//	}

public void displayTaxiCompanyList(TaxiCompanyInfo[] listTaxiCompanies) {
	mapView.displayTaxiCompanyList(listTaxiCompanies);

}

}
